package com.vbobot.demo.spring.nacos.client;

import static com.vbobot.demo.spring.nacos.client.SupportGetBodyInterceptor.needConvertToGet;

import java.lang.reflect.Field;
import okhttp3.Call;
import okhttp3.EventListener;
import okhttp3.Request;

/**
 * @author Bobo
 * @date 2023/2/2
 */
public class SupportGetBodyEventListener2 extends EventListener {

    @Override
    public void requestHeadersStart(Call call) {
        super.requestHeadersStart(call);
        // 开始的时候，处理没用，request不是同一个
    }

    @Override
    public void requestHeadersEnd(Call call, Request req) {
        super.requestHeadersEnd(call, req);
        // 一定要改回来，不然okhttp还是不处理请求体
        changeMethod("POST", req);
    }

    static void changeMethod(String method, Request request) {
        if (request != null && needConvertToGet()) {
            try {
                Field field = Request.class.getDeclaredField("method");
                field.setAccessible(true);
                field.set(request, method);
            } catch (IllegalAccessException | NoSuchFieldException e) {
            }
        }
    }
}
